package org.jeecg.modules.product.job.ticket.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.product.job.ticket.entity.TbJobTicket;
import org.jeecg.modules.product.job.ticket.entity.TbJobTicketAuditRecord;
import org.jeecg.modules.product.job.ticket.entity.TbJobTicketEvents;
import org.jeecg.modules.product.job.ticket.entity.TbJobTicketEventsOperatingReserve;
import org.jeecg.modules.product.job.ticket.service.ITbJobTicketAuditRecordService;
import org.jeecg.modules.product.job.ticket.service.ITbJobTicketEventsOperatingReserveService;
import org.jeecg.modules.product.job.ticket.service.ITbJobTicketEventsService;
import org.jeecg.modules.product.job.ticket.service.ITbJobTicketService;
import org.jeecg.modules.product.job.ticket.vo.TbJobTicketEventsPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 电子作业票活动清单
 * @Author: jeecg-boot
 * @Date:   2024-08-08
 * @Version: V1.0
 */
@Tag(name="电子作业票活动清单")
@RestController
@RequestMapping("/TbJobTicketEvents/tbJobTicketEvents")
@Slf4j
public class TbJobTicketEventsController extends JeecgController<TbJobTicketEvents, ITbJobTicketEventsService> {
	@Autowired
	private ITbJobTicketEventsService tbJobTicketEventsService;
	@Autowired
	private ITbJobTicketService tbJobTicketService;
	@Autowired
	private ITbJobTicketEventsOperatingReserveService tbJobTicketEventsOperatingReserveService;
	@Autowired
	private ITbJobTicketAuditRecordService tbJobTicketAuditRecordService;


	/*---------------------------------主表处理-begin-------------------------------------*/
	
	/**
	 * 分页列表查询
	 *
	 * @param tbJobTicketEvents
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "电子作业票活动清单-分页列表查询")
	@Operation(summary="电子作业票活动清单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<TbJobTicketEvents>> queryPageList(TbJobTicketEvents tbJobTicketEvents,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TbJobTicketEvents> queryWrapper = QueryGenerator.initQueryWrapper(tbJobTicketEvents, req.getParameterMap());
		Page<TbJobTicketEvents> page = new Page<TbJobTicketEvents>(pageNo, pageSize);
		IPage<TbJobTicketEvents> pageList = tbJobTicketEventsService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param tbJobTicketEventsPage
	 * @return
	 */
	@AutoLog(value = "电子作业票活动清单-添加")
	@Operation(summary="电子作业票活动清单-添加")
	//@RequiresPermissions("TbJobTicketEvents:tb_job_ticket_events:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody TbJobTicketEventsPage tbJobTicketEventsPage) {
		TbJobTicketEvents tbJobTicketEvents = new TbJobTicketEvents();
		BeanUtils.copyProperties(tbJobTicketEventsPage, tbJobTicketEvents);
		tbJobTicketEventsService.saveMain(tbJobTicketEvents, tbJobTicketEventsPage.getTbJobTicketEventsOperatingReserve(),tbJobTicketEventsPage.getTbJobTicketAuditRecordList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param tbJobTicketEventsPage
	 * @return
	 */
	@AutoLog(value = "电子作业票活动清单-编辑")
	@Operation(summary="电子作业票活动清单-编辑")
	//@RequiresPermissions("TbJobTicketEvents:tb_job_ticket_events:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody TbJobTicketEventsPage tbJobTicketEventsPage) {
		TbJobTicketEvents tbJobTicketEvents = new TbJobTicketEvents();
		BeanUtils.copyProperties(tbJobTicketEventsPage, tbJobTicketEvents);
		TbJobTicketEvents tbJobTicketEventsEntity = tbJobTicketEventsService.getById(tbJobTicketEvents.getId());
		if(tbJobTicketEventsEntity==null) {
			return Result.error("未找到对应数据");
		}
		tbJobTicketEventsService.updateMain(tbJobTicketEvents, tbJobTicketEventsPage.getTbJobTicketEventsOperatingReserve(),tbJobTicketEventsPage.getTbJobTicketAuditRecordList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "电子作业票活动清单-通过id删除")
	@Operation(summary="电子作业票活动清单-通过id删除")
	//@RequiresPermissions("TbJobTicketEvents:tb_job_ticket_events:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		tbJobTicketEventsService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "电子作业票活动清单-批量删除")
	@Operation(summary="电子作业票活动清单-批量删除")
	//@RequiresPermissions("TbJobTicketEvents:tb_job_ticket_events:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tbJobTicketEventsService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "电子作业票活动清单-通过id查询")
	@Operation(summary="电子作业票活动清单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<TbJobTicketEvents> queryById(@RequestParam(name="id",required=true) String id) {
		TbJobTicketEvents tbJobTicketEvents = tbJobTicketEventsService.getById(id);
		if(tbJobTicketEvents==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tbJobTicketEvents);
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "作业活动开工准备记录通过主表ID查询")
	@Operation(summary="作业活动开工准备记录主表ID查询")
	@GetMapping(value = "/queryTbJobTicketEventsOperatingReserveByMainId")
	public Result<TbJobTicketEventsOperatingReserve> queryTbJobTicketEventsOperatingReserveListByMainId(@RequestParam(name="id",required=true) String id) {
		QueryWrapper<TbJobTicketEventsOperatingReserve> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("job_ticket_events_id", id);
		TbJobTicketEventsOperatingReserve tbJobTicketEventsOperatingReserve = tbJobTicketEventsOperatingReserveService.getOne(queryWrapper);
		return Result.OK(tbJobTicketEventsOperatingReserve);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "电子作业票审核记录通过主表ID查询")
	@Operation(summary="电子作业票审核记录主表ID查询")
	@GetMapping(value = "/queryTbJobTicketAuditRecordByMainId")
	public Result<List<TbJobTicketAuditRecord>> queryTbJobTicketAuditRecordListByMainId(@RequestParam(name="id",required=true) String id) {
		List<TbJobTicketAuditRecord> tbJobTicketAuditRecordList = tbJobTicketAuditRecordService.selectByMainId(id);
		return Result.OK(tbJobTicketAuditRecordList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tbJobTicketEvents
    */
    @RequiresPermissions("TbJobTicketEvents:tb_job_ticket_events:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TbJobTicketEvents tbJobTicketEvents) {
        return super.exportXls(request, tbJobTicketEvents, TbJobTicketEvents.class, "电子作业票活动清单");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("TbJobTicketEvents:tb_job_ticket_events:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TbJobTicketEvents.class);
    }

	 /*--------------------------------子表处理-电子作业票-begin----------------------------------------------*/
	 /**
	  * 通过主表ID查询
	  * @return
	  */
	 //@AutoLog(value = "电子作业票-通过主表ID查询")
	 @Operation(summary="电子作业票-通过主表ID查询")
	 @GetMapping(value = "/listTbJobTicketByMainId")
	 public Result<IPage<TbJobTicket>> listTbJobTicketByMainId(TbJobTicket tbJobTicket,
															   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
															   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
															   HttpServletRequest req) {
		 QueryWrapper<TbJobTicket> queryWrapper = QueryGenerator.initQueryWrapper(tbJobTicket, req.getParameterMap());
		 Page<TbJobTicket> page = new Page<TbJobTicket>(pageNo, pageSize);
		 IPage<TbJobTicket> pageList = tbJobTicketService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 /**
	  * 添加
	  * @param tbJobTicket
	  * @return
	  */
	 @AutoLog(value = "电子作业票-添加")
	 @Operation(summary="电子作业票-添加")
	 @PostMapping(value = "/addTbJobTicket")
	 public Result<String> addTbJobTicket(@RequestBody TbJobTicket tbJobTicket) {
		 tbJobTicketService.save(tbJobTicket);
		 return Result.OK("添加成功！");
	 }

	 /**
	  * 编辑
	  * @param tbJobTicket
	  * @return
	  */
	 @AutoLog(value = "电子作业票-编辑")
	 @Operation(summary="电子作业票-编辑")
	 @RequestMapping(value = "/editTbJobTicket", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> editTbJobTicket(@RequestBody TbJobTicket tbJobTicket) {
		 tbJobTicketService.updateById(tbJobTicket);
		 return Result.OK("编辑成功!");
	 }

	 /**
	  * 通过id删除
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "电子作业票-通过id删除")
	 @Operation(summary="电子作业票-通过id删除")
	 @DeleteMapping(value = "/deleteTbJobTicket")
	 public Result<String> deleteTbJobTicket(@RequestParam(name="id",required=true) String id) {
		 tbJobTicketService.removeById(id);
		 return Result.OK("删除成功!");
	 }

	 /**
	  * 批量删除
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "电子作业票-批量删除")
	 @Operation(summary="电子作业票-批量删除")
	 @DeleteMapping(value = "/deleteBatchTbJobTicket")
	 public Result<String> deleteBatchTbJobTicket(@RequestParam(name="ids",required=true) String ids) {
		 this.tbJobTicketService.removeByIds(Arrays.asList(ids.split(",")));
		 return Result.OK("批量删除成功!");
	 }

	 /**
	  * 导出
	  * @return
	  */
	 @RequestMapping(value = "/exportTbJobTicket")
	 public ModelAndView exportTbJobTicket(HttpServletRequest request, TbJobTicket tbJobTicket) {
		 // Step.1 组装查询条件
		 QueryWrapper<TbJobTicket> queryWrapper = QueryGenerator.initQueryWrapper(tbJobTicket, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<TbJobTicket> pageList = tbJobTicketService.list(queryWrapper);
		 List<TbJobTicket> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "电子作业票");
		 mv.addObject(NormalExcelConstants.CLASS, TbJobTicket.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("电子作业票报表", "导出人:" + sysUser.getRealname(), "电子作业票"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
	 }

	 /**
	  * 导入
	  * @return
	  */
	 @RequestMapping(value = "/importTbJobTicket/{mainId}")
	 public Result<?> importTbJobTicket(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<TbJobTicket> list = ExcelImportUtil.importExcel(file.getInputStream(), TbJobTicket.class, params);
				 for (TbJobTicket temp : list) {
					 temp.setEventsId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 tbJobTicketService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
	 }

	 /*--------------------------------子表处理-电子作业票-end----------------------------------------------*/

}
